package com.lab.driver;   

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lab.dto.KVMapper;
import com.lab.pojo.Monitor;
import com.lab.pojo.Sensor;
import com.lab.util.SocketMethod;
import com.lab.util.UtilTools;

/**
 * @author wuhao
 * @version 创建时间：Apr 7, 2013 9:46:04 PM
 * 类说明
 */
public class Driver_TH802 implements BaseDriver{

	int temp;
	final int TRAIN = 0x0FF;

	/** 设备地址 */
	private int addr;
	/** 功能码 */
	private int func;
	/** 字节数 */
	private int num;
	/** 温度 */
	private int addr01;
	/** 湿度 */
	private int addr02;
	/** CRC校验码 */
	private int crc;
	
	/**
	 * 获取温度
	 * 
	 * @return temperature 温度实际值(单位:摄氏度)
	 */
	public float getTemperature() {
		float temperature = ((float) this.addr01) / 10;
		return temperature;
	}

	/**
	 * 获取湿度
	 * 
	 * @return humidity 湿度实际值(单位:百分比)
	 */
	public float getHumidity() {
		float humidity = ((float) this.addr02) / 10;
		return humidity;
	}
	
	public List<KVMapper> getData() {
		
		List<KVMapper> kvList = new ArrayList<KVMapper>();
		KVMapper kv1 = new KVMapper();
		KVMapper kv2 = new KVMapper();
		kv1.setKey("RT");
		kv1.setValue(String.valueOf(getTemperature()));
		kv2.setKey("RH");
		kv2.setValue(String.valueOf(getHumidity()));
		kvList.add(kv1);
		kvList.add(kv2);
		return kvList;
	}

	public boolean init(Map<String, byte[]> ori) {
		temp = ori.get("04")[3];
		if(null==ori
				||ori.get("04")==null
				||ori.get("04").length!=9){
			return false;
		}else{
			if (temp < 0) {
				this.addr01 = 0 - ((temp + 128) * 256);
				temp = ori.get("04")[4] & TRAIN;
				this.addr01 -= temp;
			} else {
				this.addr01 = temp << 8;
				temp = ori.get("04")[4] & TRAIN;
				this.addr01 += temp;
			}
			temp = ori.get("04")[5] & TRAIN;
			this.addr02 = temp << 8;
			temp = ori.get("04")[6] & TRAIN;
			this.addr02 += temp;
	
			temp = ori.get("04")[7] & TRAIN;
			this.crc = temp << 8;
			temp = ori.get("04")[8] & TRAIN;
			this.crc += temp;
		}
		return true;
	}

	public void doSocket(Monitor monitor, Sensor sensor) throws Exception {
		// TODO Auto-generated method stub
		Socket newSocket = new Socket(monitor.getIpAddress(),Integer.parseInt(monitor.getPort()));
		newSocket.setKeepAlive(true);
		newSocket.setSoTimeout(2000);
		newSocket.setTcpNoDelay(true);
		Map<String, byte[]> ori = getByteArray(Integer.parseInt(sensor.getSensorAddress()));
		init(ori);
	}

	public Map<String, byte[]> getByteArray(int deviceAddr) {
		// TODO Auto-generated method stub
		Map<String,byte[]> map = new HashMap<String,byte[]>();
		byte[] b03 = SocketMethod.String2byteArray(SocketMethod.StringCrc(UtilTools.addZeroForNum(UtilTools.mkHexStr(deviceAddr),2)+"0400000002"));
		map.put("04", b03);
		return map;
	}

}
  